package com.wtwd.campus.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

@Component
public class GaoDeUtil {

    private static final Logger logger = LoggerFactory.getLogger(GaoDeUtil.class);
    private static final String amapUrl = "http://apilocate.amap.com/position";
    private static final String amapKey = "f87fc0304c957da8153ce80774460fa1";

    /**
     * 国外定位高德key
     */
    private static final String amapUrlGlobal = "https://app.poptel88.com/gd/position";
    private static final String amapKeyGlobal = "a254cb49ad34dcb4325903508c2bfd35";

    public static final Long EXPIRATION_TIME = 1720886400000L;

    private static final String amapGpsUrl = "https://restapi.amap.com/v3/geocode/regeo";
    private static final String GOULD_KEY = "11297510e1322379f171c5e759606347";

    public static List<String> imeiGlobal = new ArrayList<>(Arrays.asList("358317101254130", "358317101254148", "358317101254155", "358317101254163"));

    /**
     * 将经纬度getLng， getLat 通过getAMapByLngAndLat方法转换地址
     *
     * @param getLng 经度
     * @param getLat 纬度
     * @return 地址名称
     * @throws Exception
     */
    public String getAMapByLngAndLat(String getLng, String getLat) {
        if (StringUtils.isEmpty(getLng) || StringUtils.isEmpty(getLat)) {
            return "-1";
        }
        String url;
        try {
            url = Constants.GAODE_API_URL + getLng + "," + getLat
                    + "&key=" + GOULD_KEY + "&radius=0&extensions=base";
            String queryResult = getResponse(url); // 高德接品返回的是JSON格式的字符串
            if (queryResult == null) {
                return "-1";
            }
            // 将获取结果转为json 数据
//            .stringToValue(queryResult)
            JSONObject obj = JSONObject.parseObject(queryResult);
            if (obj.get("status").toString().equals("1")) {
                // 如果没有返回-1
                JSONObject regeocode = obj.getJSONObject("regeocode");
                if (regeocode.size() > 0) {
                    // 在regeocode中拿到 formatted_address 具体位置
                    String formatted = regeocode.get("formatted_address").toString();
                    return formatted;

                } else {
                    System.out.println("未找到相匹配的地址！");
                    return "-1";

                }
            } else {
                System.out.println("请求错误！");
                return "-1";
            }
        } catch (Exception e) {
            //  Auto-generated catch block
            e.printStackTrace();
        }
        return "-1";
    }


    /**
     * 0.根据地址名称得到两个地址间的距离
     *
     * @param start 起始位置
     * @param start 结束位置
     * @return 两个地址间的距离
     */
    public long getDistanceByAddress(String start, String end) {
        String startLonLat = getLonLat(start);
        String endLonLat = getLonLat(end);
        long dis = getDistance(startLonLat, endLonLat);
        return dis;
    }

    /**
     * 1.地址转换为经纬度
     *
     * @param address 地址
     * @return 经纬度
     */
    public String getLonLat(String address) {
        // 返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=" + GOULD_KEY + "&address=" + address;
        String queryResult = getResponse(queryUrl); // 高德接品返回的是JSON格式的字符串
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONObject jobJSON = JSONObject
                .parseObject(job.get("geocodes").toString().substring(1, job.get("geocodes").toString().length() - 1));
        String DZ = jobJSON.get("location").toString();
        return DZ;
    }

    /**
     * 2.根据两个定位点的经纬度算出两点间的距离
     *
     * @param startLonLat 起始经纬度
     * @param endLonLat   结束经纬度（目标经纬度）
     * @return 两个定位点之间的距离
     */
    private long getDistance(String startLonLat, String endLonLat) {
        // 返回起始地startAddr与目的地endAddr之间的距离，单位：米
        Long result = new Long(0);
        String queryUrl = "http://restapi.amap.com/v3/distance?key=" + GOULD_KEY + "&origins=" + startLonLat + "&destination="
                + endLonLat;
        String queryResult = getResponse(queryUrl);
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONArray ja = job.getJSONArray("results");
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        result = Long.parseLong(jobO.get("distance").toString());
        return result;
    }

    /**
     * 3.发送请求
     *
     * @param serverUrl 请求地址
     */
    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static JSONObject getWifiAddress(String macs, String imei) {
        HashMap<String, String> params = new HashMap<String, String>();
        String key = amapKey;
        String url = amapUrl;
        if (imeiGlobal.contains(imei) && EXPIRATION_TIME > new Date().getTime()) {
            if (checkCloneWif(macs)) {
                logger.info("国外过滤掉的imei={},macs={}", imei, macs);
                return null;
            }
            key = amapKeyGlobal;
            url = amapUrlGlobal;
            logger.info("进入高德key海外key替换url={},key={}", url, key);
        }
        params.put("accesstype", "1");
        params.put("output", "json");
        params.put("key", key);
        params.put("macs", macs);
        params.put("imei", imei);
        logger.info("send GaoDe getWifiAddress url={},param={}", url, params);
        String result = HttpUtil.gaoDeApiGet(url, params);   // get方式  使用 ？ 拼接
        logger.info("reply GaoDe getWifiAddress result={}", result);
        if (!StringUtils.isBlank(result)) {
            return JSONObject.parseObject(result);
        }
        return null;
    }

    public static JSONObject getLbsAddress(String bts, String nearBts, String imei) {
        String key = amapKey;
        String url = amapUrl;
        if (imeiGlobal.contains(imei) && EXPIRATION_TIME > new Date().getTime()) {
            key = amapKeyGlobal;
            url = amapUrlGlobal;
            logger.info("进入高德key海外key替换url={},key={}", url, key);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("accesstype", "0");
        params.put("cdma", "0");//非cdma是0，cdma是1
        params.put("network", "GSM");
        params.put("output", "json");
        params.put("key", key);
        params.put("bts", bts);
        System.out.println("bts======" + bts);
        params.put("nearbts", nearBts);
        System.out.println("nearBts======" + nearBts);
        params.put("imei", imei);
        logger.info("send GaoDe getLbsAddress url={},param={}", url, params);
        String result = HttpclientUtil.get(url, params);
        logger.info("reply GaoDe getLbsAddress result", result);
        if (!StringUtils.isBlank(result)) {
            return JSONObject.parseObject(result);
        }
        return null;
    }

    /**
     * 过滤数据返回true
     *
     * @param macs
     * @return
     */
    public static boolean checkCloneWif(String macs) {
        ArrayList<String> checkMac = new ArrayList<>(Arrays.asList(
              "86:09:86:14:f5:3e","d8:47:32:7a:bb:c8","d8:07:b6:eb:e5:ff","64:fb:92:57:d0:56",
                "f4:8c:eb:c8:b0:ab","64:fb:92:57:8b:87","64:fb:92:57:8b:86","64:fb:92:57:d0:57",
                "9c:53:22:ac:ed:6e","98:de:d0:50:2d:8e","64:fb:92:ad:1d:44","50:2b:73:b6:1b:e1",
                "64:fb:92:a9:64:c4","64:fb:92:a9:64:c3"
        ));
        List<String> macList = new ArrayList<>();
        if (StringUtils.isNotBlank(macs)) {
            String[] macDatas = macs.split("\\|");
            for (String mac : macDatas) {
                String[] split = mac.split(",");
                macList.add(split[0]);
            }
        }
        // 获取交集
        List<String> commonMacs = new ArrayList<>(checkMac);
        commonMacs.retainAll(macList);
        if (commonMacs.size()>=9){//如果命中大于10个则过滤
            return true;
        }
        return false;
        //因为测试8个命中都在国外顾不要后面的
//        int standard = 0;
//        if (macList.size() % 2 == 0) {
//            standard = macList.size() / 2;
//        } else {
//            standard = (macList.size() / 2) + 1;
//        }
//        if (standard <= commonMacs.size()) {
//            return false;
//        } else {
//            return false;
//        }
    }

    public static void main(String[] args) {
        ArrayList<String> checkMac = new ArrayList<>(Arrays.asList(
                "86:09:86:14:f5:3e", "64:fb:92:57:8b:87", "64:fb:92:57:d0:56", "f4:8c:eb:c8:b0:ab", "64:fb:92:57:8b:86",
                "64:fb:92:57:d0:57", "c0:06:c3:8d:b1:88", "64:fb:92:ad:1d:43", "9c:53:22:ac:ed:6e", "98:de:d0:50:2d:8e",
                "64:fb:92:56:cd:eb", "14:eb:b6:c4:78:42", "-88,54:af:97:ac:04:d7", "e8:48:b8:fb:32:a0", "c0:25:e9:a9:27:32"
        ));
        List<String> commonMacs = new ArrayList<>(checkMac);
        List<String> macList = new ArrayList<>();
        macList.add("86:09:86:14:f5:3e");
        commonMacs.retainAll(macList);
        System.out.println(commonMacs.size());
    }


}
